package cn.com.zsw.gblog.modules.common.service.impl;

import cn.com.zsw.gblog.config.cache.RedisCache;
import cn.com.zsw.gblog.constants.SysConstants;
import cn.com.zsw.gblog.modules.common.service.CaptchaService;
import cn.com.zsw.gblog.vo.CaptchaVO;
import cn.hutool.core.util.IdUtil;
import com.wf.captcha.ArithmeticCaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @Author ：shiwangzhou
 * @Date ：Created in 2020-09-17 11:07
 * @Description： 验证码服务
 */
@Slf4j
@Service
public class CaptchaServiceImpl implements CaptchaService {
    @Autowired
    RedisCache redisCache;

    /**
     * desc: 生成图形验证码
     *
     * @return void
     * @author: shiwangZhou
     * @date: 2020-09-17 11:08
     * @param: os
     */
    @Override
    public CaptchaVO generateImageCaptcha() {

        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48);
        // 几个数运算，默认是两个
        captcha.setLen(3);
        // 获取运算的公式：4-9+1=?
        captcha.getArithmeticString();
        // 获取运算的结果：-4
        String verCode = captcha.text();
//        String code = VerifyCodeUtils.generateVerifyCode(4);
        // 唯一标识
        String state = IdUtil.fastUUID();
        String verifyKey = SysConstants.CAPTCHA_CODE_KEY + state;
        log.info("生成的验证码是：" + verCode);
        redisCache.setCacheObject(verifyKey, verCode, SysConstants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        return new CaptchaVO(state, captcha.toBase64());
//        return new CaptchaVO(state, VerifyCodeUtils.getImageByte(code));
    }

    @Override
    public Boolean verifyCode(String state, String code) {
        String codeDb = redisCache.getCacheObject(SysConstants.CAPTCHA_CODE_KEY + state);
        return !StringUtils.isEmpty(codeDb) && code.equalsIgnoreCase(codeDb);
    }
}
